import './main.scss'

import { ref, reactive, watch, watchEffect, defineComponent, nextTick } from 'vue'

import { Search, UserFilled } from '@element-plus/icons-vue'
import { ElInput, ElScrollbar, ElCheckbox, ElIcon, ElTreeV2 } from 'element-plus'

import { createComponentName, useExpose } from '../utils'

// import { getDepartUser } from '@/api/common'
import { fetchTreeList } from '@/api/employe/employeemanage/manage'

import Dialog from '../dialog/Dialog'

import lodash from 'lodash'

type Tree = {
  id: number
  label: string
  children?: Tree[]
  check?: boolean
  type?: string
  name?: string
}

const [name, bem] = createComponentName('depart-box')

export default defineComponent({
  name,
  props: {
    show: {
      // 显示弹框
      type: Boolean,
      default: false
    },
    isMember: {
      // 是否只支持人员信息
      type: Boolean,
      default: true
    },
    multiple: {
      // 是否多选
      type: Boolean,
      default: true
    },
    selectedMember: {
      type: Array,
      default: () => []
    },
    params: {
      type: Object,
      // 部门ID department_id	1	Text	否
      // 外部联系人权限 is_wx_follow_user	默认 -1 全部 0 未开启 1 开启
      default: {
        department_id: '',
        is_wx_follow_user: -1,
      }
    }
  },

  emit: ['submit', 'update:show', 'update:isMember', 'close'],

  setup(props, { emit, slots }) {
    const treeRef = ref<InstanceType<typeof ElTreeV2>>()
    const state: any = reactive({
      title: '部门信息',
      searchName: '',
      selectedMember: [],
      depart: [] // 部门左侧树
    })
    const TreeData: any[] = []

  const defaultExpandedKeys = reactive<any[]>([])
  const defaultExpandedLevel = 1 // 默认展开的层级
    watch(
      () => props.selectedMember,
      (val) => {

        console.log(val)
        state.selectedMember = val
      },{
        immediate: true
      }
    )

    // 获取部门员工信息
    watchEffect(async () => {
      if (props.show && !state.depart?.length) {
        const params = lodash.cloneDeep(props.params)
        const data = await fetchTreeList(params)
        state.depart = filterMember(data,true)
        treeRef.value!.setExpandedKeys(defaultExpandedKeys) // 设置默认展开
        TreeData.splice(0, TreeData.length, ...state.depart)
        treeRef.value?.setData(TreeData)
      }
    })

    watch(() => props.show, val => {
      if (val && state.depart.length) {
        nextTick(() => {
          treeRef.value?.setData(filterMember(TreeData, true))
          treeRef.value?.setExpandedKeys(defaultExpandedKeys) // 设置默认展开
        })
      }
    })

    // 筛选出人员信息
    const filterMember = (data: any, isClearOther?: boolean, level?: number = 1) => {
      data = Array.isArray(data) ? data : [data]
      const arr: any[] = []
      data.forEach((item: any) => {
        if (item.users?.length > 0) {
          item.members = item.users.length
          item.children = !item.children || !item.children?.length ? item.users : [...item.children, ...item.users]
          delete item.users
        }
        if (isClearOther) {
          item.check = state.selectedMember.some((it: any) => it.id == item.id)
        } else {
          item.check = false
        }
        if (item.children?.length) {
          level <= defaultExpandedLevel && defaultExpandedKeys.push(item.id)
          item.children = filterMember(item.children, isClearOther, level + 1)
        }
        arr.push(item)
      })

      return arr
    }

    const currentChange = (v: any, data: Tree) => {
      data.check = v
      const res = JSON.parse(JSON.stringify(data))
      delete res.children
      delete res.users
      seletData(res)
    }

    // 删除选中的成员
    const removeItem = (data: any) => {
      state.selectedMember = state.selectedMember.filter((item: any) => item.id !== data.id)
      state.depart = restoreDepart(data.id, state.depart)
    }

    // 删除全部已选成员
    const removeAll = () => {
      state.selectedMember = []
      state.depart = childrenNode(false, state.depart)
    }

    // 选则部门时，全选部门成员
    const childrenNode = (check: boolean, data: any[]) => {
      const arr: any[] = []
      if (data.length) {
        data.forEach((item: any) => {
          item.check = check
          if (item.children?.length) {
            const children = childrenNode(check, item.children)
            item.children = children
          }
          arr.push(item)
        })
      }
      return arr
    }

    // 已选成员
    const seletData = (item: any) => {
      
      if (item.check) {
        state.selectedMember = [...(props.multiple ? state.selectedMember : []), item]
      } else {
        if (state.selectedMember.length) {
          state.selectedMember = state.selectedMember.filter((data: any) => item.id !== data.id)
        }
      }
      if (!props.multiple) {
        filterMember(state.depart, true)
      }
    }

    // 删除右侧选中成员 恢复左边
    const restoreDepart = (id: string, data: any) => {
      const arr: any[] = []
      data.forEach((item: any) => {
        if (item.id === id) {
          item.check = false
        } else {
          if (item.children?.length) {
            item.children = restoreDepart(id, item.children)
          }
        }
        arr.push(item)
      })
      return arr
    }

    // 查找部门的成员信息
    const restore = (data: any) => {
      const arr: any[] = []

      data.map((item: any) => {
        item.check = false
        if (item.children?.length > 0) {
          item.children = restore(item.children)
        }
        arr.push(item)
      })

      return arr
    }

    const getSelectedMember = () => state.selectedMember

    // 关闭
    const onClose = () => {
      emit('update:show', false)
      emit('close', false)
    }

    // 取消
    const onCancel = () => {
      onClose()
      emit('update:isMember', true)
    }

    // 确定
    const onSubmit = () => {
      state.selectedMember = state.selectedMember.reduce((pre, cur)=>{
        if(!pre.some(ite => ite.id == cur.id)){
          pre.push(cur)
        }
        return pre
      }, [])
      
      emit('submit', state.selectedMember)
      onCancel()
    }

    const handleSearch = lodash.debounce(() => {
      treeRef.value!.filter(state.searchName)
    }, 500)
    const handleFilterMethod = (query: string, node: any) => {
      return node.name!.includes(query)
    }

    useExpose({
      removeItem,
      removeAll,
      getSelectedMember
    })
    // is_local 0是企微1是本地
    return () => {
      const treeSlots = {
        default: ({ node, data }: any) => {
          return (
            <>
              {props.isMember ? (
                <span class="custom-tree-node">
                  {data.type == 'user' ? (
                    <ElCheckbox vModel={data.check} disabled={ data.is_local === 0 ? false : true } class="depart_member" onChange={(v) => currentChange(v, data)}>
                      <span>
                        <ElIcon class="depart_member_icon">
                          <UserFilled />
                        </ElIcon>
                        <span>{node.label}</span>
                      </span>
                    </ElCheckbox>
                  ) : (
                    <span>
                      <img class="depart_icon" src="/static/newDepart.png" alt="" />
                      <span>{node.label}</span>
                      <span>{data.is_local === 0 ? '（企微）' : '（本地）'}</span>
                    </span>
                  )}
                </span>
              ) : (
                <span class="custom-tree-node">
                  <ElCheckbox vModel={data.check} disabled={ data.is_local === 0 ? false : true } class="depart_member" onChange={(v) => currentChange(v, data)}>
                    <span>
                      {data.type == 'user' ? (
                        <ElIcon class="depart_member_icon">
                          <UserFilled />
                        </ElIcon>
                      ) : (
                        <img class="depart_icon mr2" src="/static/newDepart.png" alt="" />
                      )}
                      <span>{node.label}</span>
                      <span>{data.is_local === 0 ? '（企微）' : '（本地）'}</span>
                    </span>
                  </ElCheckbox>
                </span>
              )}
            </>
          )
        }
      }

      return (
        <Dialog vModel:show={props.show} title={state.title} width="800px" cancelText="取消" submitText="保存" onClose={onClose} onConfirm={onSubmit} onCancel={onCancel}>
          <div class={bem()}>
            <div class="depart_l">
              <ElInput vModel={state.searchName} class="search_name" placeholder="搜索部门" prefixIcon={Search} onInput={handleSearch} />
                <ElTreeV2
                  class="zw-tree-box"
                  vSlots={treeSlots}
                  ref={treeRef}
                  height={400}
                  nodeKey="id"
                  props={{
                    children: 'children',
                    label: 'name'
                  }}
                  defaultExpandAll
                  filter-method={handleFilterMethod}
                />
            </div>
            <div class="depart_r">
              <div class="depart_select_title">已选择的部门</div>
              <ElScrollbar height="400px">
                {state.selectedMember?.map((item: any, index: number) => (
                  <div class="seled_member" key={`${item.id}-${index}`}>
                    <div class="item_member">
                      {item.type == 'user' ? (
                        <ElIcon class="seled_icon">
                          <UserFilled />
                        </ElIcon>
                      ) : (
                        <img class="depart_icon" src="/static/newDepart.png" alt="" />
                      )}
                      <span class="member_name">{item.name}</span>
                    </div>
                    <ElIcon class="remove_icon" onClick={() => removeItem(item)}>
                      <close />
                    </ElIcon>
                  </div>
                ))}
              </ElScrollbar>
            </div>
          </div>
        </Dialog>
      )
    }
  }
})
